package org.example.slave.packet.execute;

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.SneakyThrows;
import org.example.slave.packet.PacketWithHeader;
import org.example.slave.util.ByteUtil;
import org.example.slave.util.LengthCodedStringReader;

/**
 * @author dingrui
 * @since 2022/2/16
 * @description
 */
@Data
@EqualsAndHashCode(callSuper = true)
public class FieldPacket extends PacketWithHeader {

    private String catalog;
    private String db;
    private String table;
    private String originalTable;
    private String name;
    private String originalName;
    private int character;
    private long length;
    private byte type;
    private int flags;
    private byte decimals;
    private String definition;

    @SneakyThrows
    @Override
    public void fromBytes(byte[] data) {
        int index = 0;
        LengthCodedStringReader reader = new LengthCodedStringReader(null, index);
        catalog = reader.readLengthCodedString(data);
        db = reader.readLengthCodedString(data);
        this.table = reader.readLengthCodedString(data);
        this.originalTable = reader.readLengthCodedString(data);
        this.name = reader.readLengthCodedString(data);
        this.originalName = reader.readLengthCodedString(data);
        index = reader.getIndex();
        //
        index++;
        //
        this.character = ByteUtil.readUnsignedShortLittleEndian(data, index);
        index += 2;
        //
        this.length = ByteUtil.readUnsignedIntLittleEndian(data, index);
        index += 4;
        //
        this.type = data[index];
        index++;
        //
        this.flags = ByteUtil.readUnsignedShortLittleEndian(data, index);
        index += 2;
        //
        this.decimals = data[index];
        index++;
        //
        index += 2;// skip filter
        //
        if (index < data.length) {
            reader.setIndex(index);
            this.definition = reader.readLengthCodedString(data);
        }
    }
}
